package com.coursehub.course.repository;

import com.coursehub.course.entity.ClassesTeacher;
import com.coursehub.course.entity.ClassesTeacherId;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 班级教师关联数据访问层
 */
@Repository
public interface ClassesTeacherRepository extends JpaRepository<ClassesTeacher, ClassesTeacherId> {
    
    /**
     * 根据班级ID查找所有班级教师关联
     */
    List<ClassesTeacher> findByClasses_ClassesId(String classesId);
    
    /**
     * 根据用户ID查找所有班级教师关联
     */
    List<ClassesTeacher> findById_UserId(String userId);
    
    /**
     * 根据班级ID和用户ID查找班级教师关联
     */
    Optional<ClassesTeacher> findById_ClassesIdAndId_UserId(String classesId, String userId);
    
    /**
     * 检查教师是否在该班级中
     */
    boolean existsById_ClassesIdAndId_UserId(String classesId, String userId);
    
    /**
     * 检查班级教师关联是否存在（自定义查询）
     */
    @Query("SELECT EXISTS(SELECT ct FROM ClassesTeacher ct WHERE ct.id.classesId = :classesId AND ct.id.userId = :userId)")
    boolean existsByClassesIdAndUserId(@Param("classesId") String classesId, @Param("userId") String userId);
    
    /**
     * 根据班级ID获取所有教师ID
     */
    @Query("SELECT ct.id.userId FROM ClassesTeacher ct WHERE ct.id.classesId = :classesId")
    List<String> findTeacherIdsByClassesId(@Param("classesId") String classesId);
    
    /**
     * 根据用户ID获取所有班级ID
     */
    @Query("SELECT ct.id.classesId FROM ClassesTeacher ct WHERE ct.id.userId = :userId")
    List<String> findClassesIdsByUserId(@Param("userId") String userId);
    
    /**
     * 根据课程ID和用户ID查找班级教师关联
     */
    @Query("SELECT ct FROM ClassesTeacher ct WHERE ct.classes.courseId = :courseId AND ct.id.userId = :userId")
    List<ClassesTeacher> findByCourseIdAndUserId(@Param("courseId") String courseId, @Param("userId") String userId);
}